<?php
namespace user;
use View;
use Response;
use BaseController;
use Auth;
use User;
use Link;
use Input;
use Validator;
use Redirect;

class LinksController extends BaseController {

	public function index($id = 0){
		//存在id值则为修改
		if($id){
			$sub_title = '修改链接';
			$one = Link::find($id);
		}else{
			$sub_title = '添加链接';
			$one = '';
		}
		$links = Link::where('user_id',Auth::id())->get();
		return View::make('user.links.index')->with('title','友情链接')->with('sub_title',$sub_title)->with('links',$links)->with('one',$one);
	}

	public function doAdd(){
		$rules = array(
			'name' => 'required|min:2',
			'url' => 'required|url',
			'sort_order' => 'integer'
		);

		$validator = Validator::make(Input::all(),$rules);
		if($validator->passes()){
			//存在id则进行更新,否则进行新增
			if($id = Input::get('id')){
				$link = Link::find($id);
				$link->name = Input::get('name');
				$link->url = Input::get('url');
				$link->sort_order = Input::get('sort_order');
			}else{
				$link = Link::create(Input::only('name','url','sort_order'));
				$link->user_id = Auth::id();
			}

			if($link->save()){
				return Redirect::back()->with('message',array('type'=>'success','content'=>'操作成功'));
			}else{
				return Redirect::back()->with('message',array('type'=>'danger','content'=>'操作失败'))->withInput();
			}
		}else{
			return Redirect::back()->withInput()->withErrors($validator);
		}
	}

	public function delete($id){
		$link = Link::find($id);
		if($link && $link->delete()){
			return Redirect::to('user/links')->with('message',array('type'=>'danger','content'=>'删除成功'));
		}else{
			return Redirect::to('user/links')->with('message',array('type'=>'success','content'=>'删除失败'));
		}
	}


}